#!/usr/bin/env python
"""
It takes a FASTQ file and coverts all ambigous nucleotides to the closest unabigous nucleotide.



Author: Daniel Nicorici, Daniel.Nicorici@gmail.com

Copyright (c) 2009-2014 Daniel Nicorici

This file is part of FusionCatcher.

FusionCatcher is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

FusionCatcher is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with FusionCatcher (see file 'COPYING.txt').  If not, see
<http://www.gnu.org/licenses/>.

By default, FusionCatcher is running BLAT aligner
<http://users.soe.ucsc.edu/~kent/src/> but it offers also the option to disable
all its scripts which make use of BLAT aligner if you choose explicitly to do so.
BLAT's license does not allow to be used for commercial activities. If BLAT
license does not allow to be used in your case then you may still use
FusionCatcher by forcing not use the BLAT aligner by specifying the option
'--skip-blat'. Fore more information regarding BLAT please see its license.

Please, note that FusionCatcher does not require BLAT in order to find
candidate fusion genes!

This file is not running/executing/using BLAT.
"""
import os
import sys
import optparse
import string
import gc

def reads_from_fastq_file(f_name,size_read_buffer=10**8):
    fid=open(f_name,'r')
    piece=[]
    while True:
        gc.disable()
        lines=fid.readlines(size_read_buffer)
        gc.enable()
        if not lines:
            break
        for a_line in lines:
            piece.append(a_line[:].strip())
            if len(piece)==4:
                yield piece
                piece=[]
    if piece:
        yield piece
    fid.close()

class lines_to_file:
    def __init__(self,file_name,size_buffer=10**8):
        self.file_name=file_name
        if file_name:
            self.file_handle=open(file_name,'w')
        self.size_buffer=size_buffer
        self.data=[]
        self.size=0
    def add_line(self,line):
        line=line.rstrip('\r\n')+'\n'
        self.data.append(line)
        self.size=self.size+len(line)
        if self.size>self.size_buffer:
            self.__write_buffer()
    def add_lines(self,lines):
        lines=[line.rstrip('\r\n')+'\n' for line in lines]
        self.data.extend(lines)
        self.size=self.size+sum([len(line) for line in lines])
        if self.size>self.size_buffer:
            self.__write_buffer()
    def __write_buffer(self):
        self.file_handle.writelines(self.data)
        self.size=0
        self.data=[]
    def is_filename_valid(self):
        if self.file_name:
            return True
        else:
            return False
    def close(self):
        if self.is_filename_valid():
            if self.data:
                self.__write_buffer()
            self.file_handle.close()
            self.file_name = None            
    def __del__(self):
        self.close()

if __name__=='__main__':

    #command line parsing

    usage="%prog [options]"
    description="""It takes a FASTQ file and coverts all ambigous nucleotides to A."""
    version="%prog 0.10 beta"

    parser=optparse.OptionParser(usage=usage,description=description,version=version)

    parser.add_option("--input",
                      action="store",
                      type="string",
                      dest="input_filename",
                      help="""The input file (in FASTQ format) containing the short reads to be converted.""")

    parser.add_option("--output",
                      action="store",
                      type="string",
                      dest="output_filename",
                      help="""The output FASTQ file containing the short reads where all ambigous nucleotides has been converted to closest unambigous nucleotide.""")

    (options,args)=parser.parse_args()

    # validate options
    if not (options.input_filename and
            options.output_filename
            ):
        print "Author: Daniel Nicorici, E-mail: Daniel.Nicorici@gmail.com"
        parser.print_help()
        sys.exit(1)

    print "Starting..."
    ttable=string.maketrans('URYMKWSBDHVN-','TACAGACCAAAAA')
    data=lines_to_file(options.output_filename)
    for reads in reads_from_fastq_file(options.input_filename):
        gc.disable()
        reads[1] = reads[1].upper().translate(ttable)
        reads[2] = '+'
        reads[0] = reads[0].replace(" ","_")
        gc.enable()
        data.add_lines(reads)

    print "Done."
